//
//  ArticleViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/12.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

class ArticleViewController: KMViewController {

    fileprivate let cellId = "articleCell"
    
    fileprivate var dataArray = [ArticleModel]()
    
    var cardType = "" //信用卡类型
    var titleText = ""
    
    var tableView : UITableView!
    
    fileprivate var page = 1 //页
    
    init(type:String,title:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.cardType = type
        self.titleText = title
        
        self.title = self.titleText + creditCard + self.cardType
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createTableView()
        self.tableView.mj_header.beginRefreshing() //开始刷新

    }
    
    //MARK: 创建tableView
    fileprivate func createTableView() {
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        tableView.register(ArticleCell.self, forCellReuseIdentifier: cellId)
        tableView.separatorStyle = .none
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        KMTool.setRefresh(with: tableView, headerAction: {[weak self] in
            
                self?.refreshData()
        }) {[weak self] in
                self?.loadMoreData()
        }
    }
    
    // MARK: 下拉刷新数据
    fileprivate func refreshData() {
        self.page = 1
        getData()
    }
    // MARK: 上拉加载更多数据
    fileprivate func loadMoreData() {
        if self.tableView.mj_header.isRefreshing {
            self.tableView.mj_footer.endRefreshing()
            return
        }
        
        self.page += 1
        getData()
    }
    
    //MARK: 获取数据
    fileprivate func getData() {
        
        KMTool.requestMethod(.get, URLString: url_cardArticle, parameters: ["bank":self.titleText,"p":self.page,"cate":self.cardType], success: { (value, json) in
            
            if self.page == 1 {
                self.dataArray.removeAll()
            }
            
                if let dic = json.dictionaryObject {
                    
                    for i in 0..<(dic.count - 2) {
                        
                        if let item = dic["\(i)"] as? [String:Any] {
                            let model = ArticleModel.setModel(with: item)
                            self.dataArray.append(model)
                        }else{
                            break
                        }
                    }
                    
                    self.tableView.reloadData()
                }
            
                //结束刷新
                self.tableView.mj_header.endRefreshing()
                self.tableView.mj_footer.endRefreshing()
        }) {
                self.tableView.mj_header.endRefreshing()
                self.tableView.mj_footer.endRefreshing()
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}

extension ArticleViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 100)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? ArticleCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let urlString = "https://www.kameng98.com/posts/" + dataArray[indexPath.row].id!
        let title = self.titleText + creditCard + self.cardType
        let model = dataArray[indexPath.row]
        
        let webVC = WebViewController.init(urlString: urlString, title: title, shareImage: nil, shareText: model.posts_excerpt, shareTitle: model.posts_title)
        webVC.removeElements = ["crumbs mblock","mblock mblocks","mfooter mblock footer1"]
        webVC.removeIds = ["xiong_div"]
        self.navigationController?.pushViewController(webVC, animated: true)
        
    }
    
}
